﻿using System.IO;
using System.Linq;
using System.Reflection;

namespace System
{
	internal static partial class PackedResources
	{
		public static Stream GetStream(string resourceName, string assemblyName = null)
		{
			Assembly assembly = (assemblyName == null) ? Assembly.GetExecutingAssembly() : Assembly.LoadFrom(assemblyName);
			return GetStream(resourceName, assembly);
		}

		public static Stream GetStream(string resourceName, Assembly assembly)
		{
			string[] resourceNames = assembly.GetManifestResourceNames();
			if (!resourceNames.Contains(resourceName))
			{
				resourceName = string.Format("{0}.{1}", assembly.GetName().Name, resourceName);
			}
			if (!resourceNames.Contains(resourceName))
			{
				throw new Exception(string.Format("Resource missing: {0}", resourceName));
			}
			return assembly.GetManifestResourceStream(resourceName);
		}

		public static string GetString(string resourceName, string assemblyName = null)
		{
			Assembly assembly = (assemblyName == null) ? Assembly.GetExecutingAssembly() : Assembly.LoadFrom(assemblyName);
			return GetString(resourceName, assembly);
		}

		public static string GetString(string resourceName, Assembly assembly)
		{
			using (Stream stream = GetStream(resourceName, assembly))
			{
				using (StreamReader reader = new StreamReader(stream))
				{
					return reader.ReadToEnd();
				}
			}
		}
	}
}